<?php

namespace app\common\component;

use think\Request;

/**
 * 入参过滤类
 * Class Filter
 * @package app\common\component
 */
class Filter
{
    /** @var null 单例 */
    private static $instance = null;

    /**
     * 构造函数
     * Filter constructor.
     */
    private function __construct()
    {
    }

    /**
     * 获取实例
     * @param Request $request
     * @return null
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    /**
     * ajax入参校验
     * @param Request $request
     * @throws \think\Exception
     */
    public function paramValid(Request $request)
    {
        $actionName = $request->action();
        if (substr($actionName, -4) == 'post' || isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") {
            $paramArray = json_decode(file_get_contents('php://input'), true);
            if ($paramArray === false || !is_array($paramArray)) {
                throw new \think\Exception('访问方式错误', ErrorCode::RESPONSE_FAIL);
            }

            $class = '\app\\' . $request->module() . '\\filter\\' . $request->controller() . 'Filter';
            if ($paramArray === false || !is_array($paramArray)) {
                throw new \think\Exception('验证类不存在', ErrorCode::RESPONSE_FAIL);
            }

            $filterInstance = new $class;
            if (method_exists($filterInstance, $actionName)) {
                Param::$inputParams = $paramArray;
                $filterInstance->{$actionName}();
                Param::$inputParams = [];
            } else {
                throw new \think\Exception('验证类方法不存在', ErrorCode::RESPONSE_FAIL);
            }
        }
    }
}